package com.ruoyi.web.controller.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ChineseToPinyin;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.fs.domain.*;
import com.ruoyi.fs.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * api
 *
 * @author ruoyi
 */
@Anonymous
@RestController
@RequestMapping("/data")
public class DataController extends BaseController {

    @Autowired
    private IFsAddressService fsAddressService;
    @Autowired
    private IFsCourtService fsCourtService;
    @Autowired
    private IFsLawyerService fsLawyerService;
    @Autowired
    private IFsCaseService fsCaseService;
    @Autowired
    private IFsClientService fsClientService;
    @Autowired
    private IFsCaseExamineService fsCaseExamineService;
    @Autowired
    private IFsCapitalService fsCapitalService;
    @Autowired
    private IFsTaskService fsTaskService;
    @Autowired
    private IFsTodoListService fsTodoListService;
    @Autowired
    private IFsFullViewService fsFullViewService;
    @Autowired
    private ISysDictTypeService sysDictTypeService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private ISysUserService sysUserService;

    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 测试
     */
    @GetMapping("/test")
    public AjaxResult test(SysDept dept) {
        return success("test");
    }

    /**
     * 添加地址
     */
    @GetMapping("/initAddress")
    public AjaxResult initAddress() {
        String url = "https://lspt.court.gov.cn/tap-ref-server/ref-server/api/v1/codeTypes/11202858/codes";
        String result = HttpUtils.sendGet(url);
        JSONArray ary = JSONArray.parseArray(result);
        Iterator<Object> iterator = ary.iterator();
        while (iterator.hasNext()) {
            JSONObject obj = (JSONObject) iterator.next();
            // 处理JsonObject
            String code = obj.getString("code");
            String pid = obj.getString("pid");
            String name = obj.getString("name");
            int order = obj.getIntValue("order");
            FsAddress address = new FsAddress();
            address.setCode(code);
            address.setPid(pid);
            address.setName(name);
            address.setPcode("000000");
            address.setOrder(order);
            fsAddressService.insertFsAddress(address);
            inserChildAddress(code);
        }
        return success("test");
    }

    private void inserChildAddress(String pcode) {
        String url = "https://lspt.court.gov.cn/ls-lspt/codeTypes/11202843/codes?parentCode=" + pcode + "&isDirect=true";
        String result = HttpUtils.sendGet(url);
        if (StringUtils.isNotBlank(result)) {
            try {
                Thread.sleep(500);
                JSONArray ary = JSONArray.parseArray(result);
                Iterator<Object> iterator = ary.iterator();
                while (iterator.hasNext()) {
                    JSONObject obj = (JSONObject) iterator.next();
                    // 处理JsonObject
                    String code = obj.getString("code");
                    String pid = obj.getString("pid");
                    String name = obj.getString("name");
                    int order = obj.getIntValue("order");
                    FsAddress address = new FsAddress();
                    address.setCode(code);
                    address.setPid(pid);
                    address.setName(name);
                    address.setPcode(pcode);
                    address.setOrder(order);
                    fsAddressService.insertFsAddress(address);
                    inserChildAddress(code);
                }
            } catch (Exception e) {
            }
        }
    }


    /**
     * 添加法院
     */
    @GetMapping("/initCourt")
    public AjaxResult initCourt() {
        String url = "https://lspt.court.gov.cn/tap-ref-server/ref-server/api/v1/codeTypes/11202985/codes";
        String result = HttpUtils.sendGet(url);
        JSONArray ary = JSONArray.parseArray(result);
        Iterator<Object> iterator = ary.iterator();
        while (iterator.hasNext()) {
            JSONObject obj = (JSONObject) iterator.next();
            String code = obj.getString("code");
            String name = obj.getString("name");
            inserCourtByCode(code, name);
        }
        return success("test");
    }

    private void inserCourtByCode(String sfid, String name) {
        String url = "https://lspt.court.gov.cn/ls-lspt/api/v1/fys?sfid=" + sfid + "&fymc=";
        String result = HttpUtils.sendGet(url);
        if (StringUtils.isNotBlank(result)) {
            try {
                Thread.sleep(500);
                JSONArray ary = JSONArray.parseArray(result);
                Iterator<Object> iterator = ary.iterator();
                while (iterator.hasNext()) {
                    JSONObject obj = (JSONObject) iterator.next();
                    String fyid = obj.getString("fyid");
                    String fymc = obj.getString("fymc");
                    FsCourt court = new FsCourt();
                    court.setFyid(fyid);
                    court.setFymc(fymc);
                    court.setSfid(sfid);
                    court.setSfmc(name);
                    String unit = getLastUnit(fymc);

                    List<FsAddress> addressList = fsAddressService.selectFsAddressByName(name);
                    FsAddress fysf = null;
                    if (!addressList.isEmpty()) {
                        fysf = addressList.get(0);
                    }
                    addressList = fsAddressService.selectFsAddressByName(unit);
                    if (!addressList.isEmpty()) {
                        String dz = "";
                        String code = "";
                        for (int i = 0; i < addressList.size(); i++) {
                            FsAddress q = addressList.get(i);
                            if (!q.getPcode().equals("000000")) {
                                FsAddress s = fsAddressService.selectFsAddressByCode(q.getPcode());
                                if (!s.getPcode().equals("000000")) {
                                    FsAddress sf = fsAddressService.selectFsAddressByCode(s.getPcode());
                                    if (sf.getCode().equals(fysf.getCode())) {
                                        code = q.getCode();
                                        dz = sf.getName() + s.getName() + q.getName();
                                    }
                                } else {
                                    if (s.getCode().equals(fysf.getCode())) {
                                        code = q.getCode();
                                        dz = s.getName() + q.getName();
                                    }
                                }
                            } else {
                                code = q.getCode();
                                dz = q.getName();
                            }
                        }
                        court.setDz(dz);
                        court.setDzCode(code);
                    } else {
                        court.setDz(fysf.getName());
                        court.setDzCode(fysf.getCode());
                    }
                    fsCourtService.insertFsCourt(court);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String getLastUnit(String dz) {
        dz = dz.replace("人民法院", "");
        int l1 = dz.indexOf("省") + 1;
        String last = "";
        if (l1 > 0) {
            last = dz.substring(l1, dz.length());
        } else {
            last = dz;
        }
        int l2 = last.indexOf("市") + 1;
        String s = "";
        if (l2 > 0) {
            s = last.substring(0, l2);
            last = last.substring(l2, last.length());
        }
        int l3 = last.indexOf("市") + 1;
        String s2 = "";
        if (l3 > 0) {
            s2 = last.substring(0, l3);
            last = last.substring(l3, last.length());
        }
        int l4 = last.indexOf("区") + 1;
        String q = "";
        if (l4 > 0) {
            q = last.substring(0, l4);
            last = last.substring(l4, last.length());
        }
        int l5 = last.indexOf("县") + 1;
        String x = "";
        if (l5 > 0) {
            x = last.substring(0, l5);
        }
        if (StringUtils.isNotBlank(x)) {
            return x;
        } else if (StringUtils.isNotBlank(q)) {
            return q;
        } else if (StringUtils.isNotBlank(s2)) {
            return s2;
        } else if (StringUtils.isNotBlank(s)) {
            return s;
        }
        return null;
    }


    /**
     * 添加字典
     */
    @GetMapping("/initDict")
    public AjaxResult initDict() {
        String url = "https://lspt.court.gov.cn/tap-ref-server/ref-server/api/v1/codeTypes/11202825/codes";
        String result = HttpUtils.sendGet(url);
        JSONArray ary = JSONArray.parseArray(result);
        Iterator<Object> iterator = ary.iterator();
        long num = 1;
        while (iterator.hasNext()) {
            JSONObject obj = (JSONObject) iterator.next();
            String code = obj.getString("code");
            String name = obj.getString("name");
            SysDictData data = new SysDictData();
            data.setDictType("fs_gw_mz");
            data.setDictLabel(name);
            data.setDictValue(code);
            data.setDictSort(num);
            data.setListClass("default");
            data.setStatus("0");
            data.setIsDefault("N");
            sysDictDataService.insertDictData(data);
            num++;
        }
        return success("test");
    }


    /**
     * 添加律师
     */
    @GetMapping("/initLs")
    public AjaxResult initLs() {
        String url = "https://lspt.court.gov.cn/ls-yzt/api/v1/yhxx";
        String result = HttpUtils.sendGet(url);
        JSONObject obj = JSONObject.parseObject(result);
        String xm = obj.getString("xm");
        String sfzh = obj.getString("sfzh");
        String zyjg = obj.getString("zyjg");
        String zyzh = obj.getString("zyzh");
        String bh = obj.getString("bh");
        String sjhm = obj.getString("sjhm");
        int zylb = obj.getIntValue("zylb");
        int xb = obj.getIntValue("xb");

        SysUser user = sysUserService.selectUserByNickName(xm);
        if (user == null) {
            user.setNickName(xm);
            user.setUserName(ChineseToPinyin.toPinyin(xm));
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            user.setSex(xb + "");
            user.setRoleId(100L);
            user.setDeptId(104L);
            user.setStatus("0");
            user.setPhonenumber(sjhm);
            sysUserService.insertUser(user);
        }
        FsLawyer lawyer = fsLawyerService.selectFsLawyerByBh(bh);
        if (lawyer == null) {
            lawyer = new FsLawyer();
        }
        lawyer.setBh(bh);
        lawyer.setZyjg(zyjg);
        lawyer.setSfzh(sfzh);
        lawyer.setXb(xb);
        lawyer.setXm(xm);
        lawyer.setZylb(zylb);
        lawyer.setSjhm(sjhm);
        lawyer.setZyzh(zyzh);
        lawyer.setUserId(user.getUserId());
        if (lawyer.getId() != null) {
            fsLawyerService.updateFsLawyer(lawyer);
        } else {
            fsLawyerService.insertFsLawyer(lawyer);
        }
        return success("test");
    }


    /**
     * 按照立案状态抓取案件
     */
    @GetMapping("/initAllCase")
    public AjaxResult initAllCase(@RequestParam(value = "zt", required = true) String zt) {
        int num = 0;
        String url = "https://lspt.court.gov.cn/ls-wsla/api/v2/layys?ajmc=&ah=&jbfy=&layyZt=" + zt + "&offset=0&limit=1000";
        String result = HttpUtils.sendGet(url);
        JSONObject res = JSONObject.parseObject(result);
        JSONArray ary = res.getJSONArray("data");
        Iterator<Object> iterator = ary.iterator();
        while (iterator.hasNext()) {
            JSONObject obj = (JSONObject) iterator.next();
            String ah = obj.getString("ah");
            String bh = obj.getString("bh");
            FsCase c = editCase(bh, ah);
            System.out.println(num++ + "案件：" + c.getAjmc());
            sleep(100);
            editCaseDetailInfo(bh, c);
            sleep(100);
            initShByBh(bh);
            sleep(100);
        }
        return success("initAllCase");
    }

    private void sleep(int time) {
        try {
            Thread.sleep(time);
        } catch (Exception e) {

        }
    }

    /**
     * 添加律师
     */
    @GetMapping("/initCase")
    public AjaxResult initCase(@RequestParam(value = "bh", required = true) String bh) {
        FsCase c = editCase(bh, null);
        editCaseDetailInfo(bh, c);
        initSh(bh);
        return success(c);
    }

    private FsCase editCase(String bh, String ah) {
        String url = "https://lspt.court.gov.cn/ls-wsla/api/v2/layy/" + bh;
        String result = HttpUtils.sendGet(url);
        JSONObject obj = JSONObject.parseObject(result);

        String ajbh = obj.getString("bh");
        String bhLs = obj.getString("bhLs");
        String ajlx = obj.getString("ajlx");
        String ajlxMc = obj.getString("ajlxMc");
        String ajmc = obj.getString("ajmc");
        String bzqx = obj.getString("bzqx");
        String fyid = obj.getString("fyid");
        String fymc = obj.getString("fymc");
        String sqbdje = obj.getString("sqbdje");
        String sqlaay = obj.getString("sqlaay");
        String sqlaayMc = obj.getString("sqlaayMc");
        String sqlx = obj.getString("sqlx");
        String sqlxMc = obj.getString("sqlxMc");
        String zt = obj.getString("zt");
        String cjsj = obj.getString("cjsj");
        String gxsj = obj.getString("zhxgsj");

        String cjrId = obj.getString("cjrId");
        FsLawyer lawyer = fsLawyerService.selectFsLawyerByBh(cjrId);
        FsCase c = fsCaseService.selectFsCaseByBh(ajbh);
        if (c == null) {
            c = new FsCase();
        }
        c.setBh(ajbh);
        if (StringUtils.isNotBlank(ah)) c.setAh(ah);
        if (StringUtils.isNotBlank(bhLs)) c.setBhLs(bhLs);
        if (StringUtils.isNotBlank(ajlx)) c.setAjlx(ajlx);
        if (StringUtils.isNotBlank(ajlxMc)) c.setAjlxMc(ajlxMc);
        if (StringUtils.isNotBlank(ajmc)) c.setAjmc(ajmc);
        if (StringUtils.isNotBlank(bzqx)) c.setBzqx(Integer.parseInt(bzqx));
        if (StringUtils.isNotBlank(fyid)) c.setFyid(fyid);
        if (StringUtils.isNotBlank(fymc)) c.setFymc(fymc);
        if (StringUtils.isNotBlank(sqbdje)) c.setSqbdje(new BigDecimal(sqbdje));
        if (StringUtils.isNotBlank(sqlaay)) c.setSqlaay(Integer.parseInt(sqlaay));
        if (StringUtils.isNotBlank(sqlaayMc)) c.setSqlaayMc(sqlaayMc);
        if (StringUtils.isNotBlank(sqlx)) c.setSqlx(sqlx);
        if (StringUtils.isNotBlank(sqlxMc)) c.setSqlxMc(sqlxMc);
        if (StringUtils.isNotBlank(zt)) c.setZt(Integer.parseInt(zt));
        if (StringUtils.isNotBlank(cjsj)) c.setCjsj(cjsj);
        if (StringUtils.isNotBlank(gxsj)) c.setGxsj(gxsj);
        if (StringUtils.isNotBlank(cjrId)) c.setLsbh(cjrId);
        if (lawyer != null) {
            c.setOwnerId(lawyer.getId());
            c.setOwner(lawyer.getXm());
        }
        if (c.getId() != null) {
            fsCaseService.updateFsCase(c);
        } else {
            fsCaseService.insertFsCase(c);
        }
        return c;
    }

    private void editCaseDetailInfo(String bh, FsCase c) {
        String url = "https://lspt.court.gov.cn/ls-wsla/api/v2/layy/" + bh + "/layyxx";
        String result = HttpUtils.sendGet(url);
        JSONObject obj = JSONObject.parseObject(result);
        JSONArray dsrList = obj.getJSONArray("dsrList");
        Iterator<Object> iterator = dsrList.iterator();
        Long ygId = null;
        Long bgId = null;
        String ygbh = null;
        String bgbh = null;
        while (iterator.hasNext()) {
            JSONObject dsrAry = (JSONObject) iterator.next();
            JSONArray list = dsrAry.getJSONArray("list");
            String ssdw = dsrAry.getString("ssdw");
            JSONObject dsr = (JSONObject) list.get(0);
            String dsrbh = dsr.getString("bh");
            String dsrlx = dsr.getString("dsrlx");
            String xm = dsr.getString("xm");
            String xb = dsr.getString("xb");
            String nl = dsr.getString("nl");
            String mz = dsr.getString("mz");
            String csrq = dsr.getString("csrq");
            String dzlx = dsr.getString("dzlx");
            String dz = dsr.getString("dz");
            String dwmc = dsr.getString("dwmc");
            String zy = dsr.getString("zy");
            String gzdw = dsr.getString("gzdw");
            String dwxz = dsr.getString("dwxz");
            String zzlx = dsr.getString("zzlx");
            String zzh = dsr.getString("zzh");
            String zybsjgszd = dsr.getString("zybsjgszd");
            String fddbr = dsr.getString("fddbr");
            String fddbrzw = dsr.getString("fddbrzw");
            String zjlx = dsr.getString("zjlx");
            String zjhm = dsr.getString("zjhm");
            String sjhm = dsr.getString("sjhm");
            String gddh = dsr.getString("gddh");
            String cjsj = dsr.getString("cjsj");
            String zymc = null;
            if (StringUtils.isNotBlank(zy)) {
                zymc = sysDictDataService.selectDictLabel("fs_gw_zy", zy);
            }

            FsClient client = fsClientService.selectFsClientByBh(dsrbh);
            if (client == null) {
                client = new FsClient();
            }
            client.setBh(dsrbh);
            client.setDsrlx(Integer.parseInt(dsrlx));
            if (StringUtils.isNotBlank(xm)) client.setXm(xm);
            if (StringUtils.isNotBlank(xb)) client.setXb(Integer.parseInt(xb));
            if (StringUtils.isNotBlank(nl)) client.setNl(Integer.parseInt(nl));
            if (StringUtils.isNotBlank(mz)) client.setMz(Integer.parseInt(mz));
            if (StringUtils.isNotBlank(csrq)) client.setCsrq(csrq);
            if (StringUtils.isNotBlank(dzlx)) client.setDzlx(Integer.parseInt(dzlx));
            if (StringUtils.isNotBlank(dz)) client.setDz(dz);
            if (StringUtils.isNotBlank(dwmc)) client.setDwmc(dwmc);
            if (StringUtils.isNotBlank(zy)) client.setZy(Integer.parseInt(zy));
            if (StringUtils.isNotBlank(zymc)) client.setZymc(zymc);
            if (StringUtils.isNotBlank(gzdw)) client.setGzdw(gzdw);
            if (StringUtils.isNotBlank(dwxz)) client.setDwxz(Integer.parseInt(dwxz));
            if (StringUtils.isNotBlank(zzlx)) client.setZzlx(Integer.parseInt(zzlx));
            if (StringUtils.isNotBlank(zzh)) client.setZzh(zzh);
            if (StringUtils.isNotBlank(zybsjgszd)) client.setZybsjgszd(zybsjgszd);
            if (StringUtils.isNotBlank(fddbr)) client.setFddbr(fddbr);
            if (StringUtils.isNotBlank(fddbrzw)) client.setFddbrzw(fddbrzw);
            if (StringUtils.isNotBlank(zjlx)) client.setZjlx(Integer.parseInt(zjlx));
            if (StringUtils.isNotBlank(zjhm)) client.setZjhm(zjhm);
            if (StringUtils.isNotBlank(sjhm)) client.setSjhm(sjhm);
            if (StringUtils.isNotBlank(gddh)) client.setGddh(gddh);
            if (StringUtils.isNotBlank(cjsj)) client.setCjsj(cjsj);
            if (client.getId() != null) {
                fsClientService.updateFsClient(client);
            } else {
                fsClientService.insertFsClient(client);
            }
            if ("1".equals(ssdw)) {
                ygbh = dsrbh;
                ygId = client.getId();
                FsCapital capital = fsCapitalService.selectFsCapitalByName(xm);
                if (capital == null) {
                    capital = new FsCapital();
                }
                if (StringUtils.isNotBlank(dwmc)) capital.setDwmc(dwmc);
                if (StringUtils.isNotBlank(dwxz)) capital.setDwxz(Integer.parseInt(dwxz));
                if (StringUtils.isNotBlank(zzh)) capital.setZzh(zzh);
                if (StringUtils.isNotBlank(zybsjgszd)) capital.setZybsjgszd(zybsjgszd);
                if (StringUtils.isNotBlank(fddbr)) capital.setFddbr(fddbr);
                if (StringUtils.isNotBlank(fddbrzw)) capital.setFddbrzw(fddbrzw);
                if (StringUtils.isNotBlank(zjhm)) capital.setZjhm(zjhm);
                if (StringUtils.isNotBlank(sjhm)) capital.setSjhm(sjhm);
                if (StringUtils.isNotBlank(gddh)) capital.setGddh(gddh);
                if (StringUtils.isNotBlank(cjsj)) capital.setCjsj(cjsj);
                if (capital.getId() != null) {
                    fsCapitalService.updateFsCapital(capital);
                } else {
                    fsCapitalService.insertFsCapital(capital);
                }
            } else {
                bgbh = dsrbh;
                bgId = client.getId();
            }
        }
        c.setYg(ygId);
        c.setYgbh(ygbh);
        c.setBg(bgId);
        c.setBgbh(bgbh);
        fsCaseService.updateFsCase(c);
    }

    /**
     * 添加审核
     */
    @GetMapping("/initSh")
    public AjaxResult initSh(@RequestParam(value = "bh", required = true) String bh) {
        return initShByBh(bh);
    }

    private AjaxResult initShByBh(String bh) {
        String url = "https://lspt.court.gov.cn/ls-wsla/api/v2/layy/" + bh + "/shjg";
        String result = HttpUtils.sendGet(url);
        JSONArray ary = JSONArray.parseArray(result);
        Iterator<Object> iterator = ary.iterator();
        long num = 1;
        FsCaseExamine last = null;
        while (iterator.hasNext()) {
            JSONObject obj = (JSONObject) iterator.next();
            String caseBh = obj.getString("bhLayy");
            String shbh = obj.getString("bh");
            String shrmc = obj.getString("shrmc");
            String jbfy = obj.getString("jbfy");
            String shsj = obj.getString("shsj");
            String shyj = obj.getString("shyj");
            String bhyymc = obj.getString("bhyymc");
            String shjg = obj.getString("shjg");
            FsCase c = fsCaseService.selectFsCaseByBh(caseBh);
            FsCaseExamine examine = fsCaseExamineService.selectFsCaseExamineByBh(shbh);
            if (examine == null) {
                examine = new FsCaseExamine();
            }
            if (c != null) {
                examine.setCaseId(c.getId());
            }
            examine.setCaseBh(caseBh);
            examine.setBh(shbh);
            if (StringUtils.isNotBlank(shrmc)) examine.setShrmc(shrmc);
            if (StringUtils.isNotBlank(jbfy)) examine.setJbfy(jbfy);
            if (StringUtils.isNotBlank(shsj)) examine.setShsj(shsj);
            if (StringUtils.isNotBlank(shyj)) examine.setShyj(shyj);
            if (StringUtils.isNotBlank(bhyymc)) examine.setBhyymc(bhyymc);
            if (StringUtils.isNotBlank(shjg)) examine.setShjg(Integer.parseInt(shjg));
            if (examine.getId() != null) {
                fsCaseExamineService.updateFsCaseExamine(examine);
            } else {
                fsCaseExamineService.insertFsCaseExamine(examine);
            }
            last = examine;
        }
        if (last != null) {
//            initTask(bh,last);
        }
        return success("test");
    }

    private void initTask(String caseBh, FsCaseExamine last) {
        FsCase c = fsCaseService.selectFsCaseByBh(caseBh);
        FsTask query = new FsTask();
        query.setCaseId(c.getId());
        query.setAjzt(c.getZt());
        List<FsTask> tasks = fsTaskService.selectFsTaskList(query);
        boolean ifNeedNew = false;
        if (tasks.isEmpty()) {
            ifNeedNew = true;
        } else {
            Date lastTaskDate = tasks.get(tasks.size() - 1).getCreateTime();
            try {
                Date caseGxsj = df.parse(c.getGxsj());
                if (caseGxsj.after(lastTaskDate)) {
                    ifNeedNew = true;
                }
            } catch (Exception e) {

            }
        }
        if (ifNeedNew) {
            if (c.getZt() == 1) {
                FsTask task = new FsTask();
                task.setAjzt(c.getZt());
                task.setCaseId(c.getId());
                task.setJb(1);
                task.setJlrq(new Date());
                task.setLsId(c.getOwnerId());
                task.setRwzt(1);
                task.setType(1);
                task.setContent("案件已提交，请及时跟进审核结果！");
                fsTaskService.insertFsTask(task);
            }
            if (c.getZt() == 2) {
                FsTask task = new FsTask();
                task.setAjzt(c.getZt());
                task.setCaseId(c.getId());
                task.setJb(3);
                task.setJlrq(new Date());
                task.setLsId(c.getOwnerId());
                task.setRwzt(1);
                task.setType(2);
                task.setContent(last.getShyj());
                fsTaskService.insertFsTask(task);
            }
            if (c.getZt() == 3) {
                FsTask task = new FsTask();
                task.setAjzt(c.getZt());
                task.setCaseId(c.getId());
                task.setJb(3);
                task.setJlrq(new Date());
                task.setLsId(c.getOwnerId());
                task.setRwzt(1);
                task.setType(3);
                task.setContent(last.getShyj());
                fsTaskService.insertFsTask(task);
            }
            if (c.getZt() == 4) {
                FsTask task = new FsTask();
                task.setAjzt(c.getZt());
                task.setCaseId(c.getId());
                task.setJb(3);
                task.setJlrq(new Date());
                task.setLsId(c.getOwnerId());
                task.setRwzt(1);
                task.setType(2);
                task.setContent(last.getShyj());
                fsTaskService.insertFsTask(task);
            }
            if (c.getZt() == 31) {
                FsTask task = new FsTask();
                task.setAjzt(c.getZt());
                task.setCaseId(c.getId());
                task.setJb(2);
                task.setJlrq(new Date());
                task.setLsId(c.getOwnerId());
                task.setRwzt(1);
                task.setType(2);
                task.setContent(last.getShyj());
                fsTaskService.insertFsTask(task);
            }
        }
    }


    /**
     * 添加代办事项
     */
    @GetMapping("/initDbsx")
    public AjaxResult initDbsx() {
        String url = "https://lspt.court.gov.cn/ls-lspt/api/v1/dbsx?dbsxLx=4";
        String result = HttpUtils.sendGet(url);
        JSONArray ary = JSONArray.parseArray(result);
        Iterator<Object> iterator = ary.iterator();
        while (iterator.hasNext()) {
            FsTodoList todoList = JSON.toJavaObject(iterator.next(), FsTodoList.class);
            FsCourt court = fsCourtService.selectFsCourtByFyId(todoList.getJbfy());
            if (court != null) {
                todoList.setJbfyMc(court.getFymc());
            }
            FsTodoList old = fsTodoListService.selectFsTodoListByBh(todoList.getBh());
            if (old == null) {
                fsTodoListService.insertFsTodoList(todoList);
            } else {
                todoList.setId(old.getId());
                fsTodoListService.updateFsTodoList(todoList);
            }
        }
        return success("test");
    }


    /**
     * 抓取审理案件
     */
    @GetMapping("/initSlaj")
    public AjaxResult initSlaj() {
        int num = 0;
        String url = "https://lspt.court.gov.cn/ls-lspt/api/v1/aj?ajmc=&ah=&jbfy=&ajzt=1&offset=0&limit=1000&ly=1&sxsqLx=";
        String result = HttpUtils.sendGet(url);
        sleep(500);
        JSONObject res = JSONObject.parseObject(result);
        JSONArray ary = res.getJSONArray("data");
        Iterator<Object> iterator = ary.iterator();
        while (iterator.hasNext()) {
            JSONObject obj = (JSONObject) iterator.next();
            String ah = obj.getString("ah");
            String bh = obj.getString("bh");
            String ajlx = obj.getString("ajlx");
            String larqStr = obj.getString("larqStr");
            editSlaj(bh, ah, ajlx, larqStr, 1);
            System.out.println(num++ + "案件：" + ah);
            sleep(500);
        }
        return success("initAllCase");
    }

    /**
     * 抓取结案案件
     */
    @GetMapping("/initJaaj")
    public AjaxResult initJaaj() {
        int num = 0;
        String url = "https://lspt.court.gov.cn/ls-lspt/api/v1/aj?ajmc=&ah=&jbfy=&ajzt=2&offset=780&limit=1000&ly=1&sxsqLx=";
        String result = HttpUtils.sendGet(url);
        sleep(500);
        JSONObject res = JSONObject.parseObject(result);
        JSONArray ary = res.getJSONArray("data");
        Iterator<Object> iterator = ary.iterator();
        while (iterator.hasNext()) {
            JSONObject obj = (JSONObject) iterator.next();
            String ah = obj.getString("ah");
            String bh = obj.getString("bh");
            String ajlx = obj.getString("ajlx");
            String larqStr = obj.getString("larqStr");
            editSlaj(bh, ah, ajlx, larqStr, 2);
            System.out.println(num++ + "案件：" + ah);
            sleep(200);
        }
        return success("initAllCase");
    }

    private void editSlaj(String bh, String ah, String ajlx, String lastUpdateDate, int ajzt) {
        String url = "https://lspt.court.gov.cn/ls-lspt/api/v1/aj/detail/" + bh + "/" + ajlx;
        String result = HttpUtils.sendGet(url);
        JSONObject json = JSONObject.parseObject(result);
        if (json.getBoolean("success") != null) {
            System.out.println(json.getString("message"));
            return;
        }

        FsLawyer lawyer = null;
        String zjhm = null;
        JSONArray dlrs = json.getJSONObject("fddlr").getJSONArray("fddlrs");
        for (int i = 0; i < dlrs.size(); i++) {
            String sfzh = ((JSONObject) dlrs.get(i)).getString("zjhm");
            FsLawyer l = fsLawyerService.selectFsLawyerByZjhm(sfzh);
            if (l != null) {
                lawyer = l;
                zjhm = sfzh;
            }
        }
        FsFullView fsFullView = fsFullViewService.selectFsFullViewByBh(bh);
        if (fsFullView == null) {
            fsFullView = new FsFullView();
            JSONArray dsrList = json.getJSONArray("dsrs");
            Iterator<Object> iterator = dsrList.iterator();
            Long ygId = null;
            Long bgId = null;
            while (iterator.hasNext()) {
                JSONObject dsr = (JSONObject) iterator.next();
                String ssdw = dsr.getString("ssdw");
                String dsrbh = dsr.getString("bh");
                String dsrlxL = dsr.getString("dsrlx");
                String dsrlx = sysDictDataService.selectDictValue("fs_gw_dsrlx", dsrlxL);
                String mc = dsr.getString("mc");
                String xbL = dsr.getString("xb");
                String xb = sysDictDataService.selectDictValue("sys_user_sex", xbL);
                String nl = dsr.getString("nl");
                String mzL = dsr.getString("mz");
                String mz = sysDictDataService.selectDictValue("fs_gw_mz", mzL);
                String csrq = dsr.getString("csrq");
                String dzlx = dsr.getString("dzlx");
                String dsrdz = dsr.getString("dsrdz");
                String zymc = dsr.getString("zy");
                String zy = sysDictDataService.selectDictValue("fs_gw_zy", zymc);
                String gzdw = dsr.getString("gzdw");
                String dwxzL = dsr.getString("dwxz");
                String dwxz = sysDictDataService.selectDictValue("fs_gw_dwxz", dwxzL);
                String zzlxL = dsr.getString("zzlx");

                String zzlx = null;
                if (StringUtils.isNotBlank(zzlxL)) {
                    if (zzlxL.contains("信用代码")) {
                        zzlx = "4";
                    } else if (zzlxL.contains("组织机构")) {
                        zzlx = "2";
                    } else {
                        zzlx = "5";
                    }
                }
                String zzh = dsr.getString("zzhm");
                String zybsjgszd = dsr.getString("zybsjgszd");
                String fddbr = dsr.getString("fddbr");
                String fddbrzw = dsr.getString("fddbrzw");
                String zjlxL = dsr.getString("zjlx");
                String zjlx = sysDictDataService.selectDictValue("fs_gw_zjlx", zjlxL);
                String dsrzjhm = dsr.getString("zjhm");
                String dbrzjhm = dsr.getString("dbrzjhm");
                String sjhm = dsr.getString("dsrsjhm");

                FsClient client = new FsClient();
                client.setBh(dsrbh);
                client.setDsrlx(Integer.parseInt(dsrlx));
                if (StringUtils.isNotBlank(xb)) client.setXb(Integer.parseInt(xb));
                if (StringUtils.isNotBlank(nl)) client.setNl(Integer.parseInt(nl));
                if (StringUtils.isNotBlank(mz)) client.setMz(Integer.parseInt(mz));
                if (StringUtils.isNotBlank(csrq)) client.setCsrq(csrq);
                if (StringUtils.isNotBlank(dzlx)) client.setDzlx(Integer.parseInt(dzlx));
                if (StringUtils.isNotBlank(zy)) client.setZy(Integer.parseInt(zy));
                if (StringUtils.isNotBlank(zymc)) client.setZymc(zymc);
                if (StringUtils.isNotBlank(gzdw)) client.setGzdw(gzdw);
                if (StringUtils.isNotBlank(dwxz)) client.setDwxz(Integer.parseInt(dwxz));
                if (StringUtils.isNotBlank(zzlx)) client.setZzlx(Integer.parseInt(zzlx));
                if (StringUtils.isNotBlank(zzh)) client.setZzh(zzh);
                if (StringUtils.isNotBlank(zybsjgszd)) client.setZybsjgszd(zybsjgszd);
                if (StringUtils.isNotBlank(fddbr)) client.setFddbr(fddbr);
                if (StringUtils.isNotBlank(fddbrzw)) client.setFddbrzw(fddbrzw);
                if (StringUtils.isNotBlank(zjlx)) client.setZjlx(Integer.parseInt(zjlx));
                if (StringUtils.isNotBlank(dsrzjhm)) client.setZjhm(dsrzjhm);
                if (StringUtils.isNotBlank(dbrzjhm)) client.setZjhm(dbrzjhm);
                if (StringUtils.isNotBlank(sjhm)) client.setSjhm(sjhm);

                if ("原告".equals(ssdw)) {
                    if (StringUtils.isNotBlank(mc)) client.setDwmc(mc);
                    if (StringUtils.isNotBlank(mc)) client.setXm(mc);
                    if (StringUtils.isNotBlank(dsrdz)) client.setZybsjgszd(dsrdz);
                    fsClientService.insertFsClient(client);
                    ygId = client.getId();
                    FsCapital capital = fsCapitalService.selectFsCapitalByName(mc);
                    if (capital == null) {
                        capital = new FsCapital();
                    }
                    if (StringUtils.isNotBlank(mc)) capital.setDwmc(mc);
                    if (StringUtils.isNotBlank(dwxz)) capital.setDwxz(Integer.parseInt(dwxz));
                    if (StringUtils.isNotBlank(zzh)) capital.setZzh(zzh);
                    if (StringUtils.isNotBlank(zybsjgszd)) capital.setZybsjgszd(zybsjgszd);
                    if (StringUtils.isNotBlank(fddbr)) capital.setFddbr(fddbr);
                    if (StringUtils.isNotBlank(fddbrzw)) capital.setFddbrzw(fddbrzw);
                    if (StringUtils.isNotBlank(zjhm)) capital.setZjhm(zjhm);
                    if (StringUtils.isNotBlank(sjhm)) capital.setSjhm(sjhm);
                    if (capital.getId() != null) {
                        fsCapitalService.updateFsCapital(capital);
                    } else {
                        fsCapitalService.insertFsCapital(capital);
                    }
                } else {
                    if (StringUtils.isNotBlank(mc)) client.setXm(mc);
                    if (StringUtils.isNotBlank(dsrdz)) client.setDz(dsrdz);
                    fsClientService.insertFsClient(client);
                    bgId = client.getId();
                }
            }

            JSONObject jbxx = json.getJSONObject("jbxx");
            JSONObject obj = jbxx.getJSONObject("laxx");
            String ajlxMc = obj.getString("ajlx");
            String ajmc = obj.getString("ajmc");
            String fymc = obj.getString("jbfy");
            FsCourt court = fsCourtService.selectFsCourtByFymc(fymc);
            String fyid = null;
            if (court != null) {
                fyid = court.getFyid();
            }
            String sqlaayMc = obj.getString("laay");
            FsCase c = fsCaseService.selectFsCaseByBh(bh);
            if (c == null) {
                c = new FsCase();
            }
            c.setBh(bh);
            if (StringUtils.isNotBlank(ah)) c.setAh(ah);
            if (StringUtils.isNotBlank(ajlx)) c.setAjlx(ajlx);
            if (StringUtils.isNotBlank(ajlxMc)) c.setAjlxMc(ajlxMc);
            if (StringUtils.isNotBlank(ajmc)) c.setAjmc(ajmc);
            if (StringUtils.isNotBlank(fyid)) c.setFyid(fyid);
            if (StringUtils.isNotBlank(fymc)) c.setFymc(fymc);
            if (StringUtils.isNotBlank(lastUpdateDate)) c.setGxsj(lastUpdateDate);
            if (StringUtils.isNotBlank(sqlaayMc)) c.setSqlaayMc(sqlaayMc);
            c.setAjzt(ajzt);
            if (lawyer != null) {
                c.setOwnerId(lawyer.getId());
                c.setOwner(lawyer.getXm());
            }
            c.setYg(ygId);
            c.setBg(bgId);
            if (c.getId() != null) {
                fsCaseService.updateFsCase(c);
            } else {
                fsCaseService.insertFsCase(c);
            }
        } else {
            FsCase c = fsCaseService.selectFsCaseByBh(bh);
            if (c != null) {
                c.setOwnerId(lawyer.getId());
                c.setOwner(lawyer.getXm());
                fsCaseService.updateFsCase(c);
            }
        }
        fsFullView.setAh(ah);
        fsFullView.setBh(bh);

        JSONObject jbxx = json.getJSONObject("jbxx");
        JSONObject laxx = jbxx.getJSONObject("laxx");
        String ajmc = laxx.getString("ajmc");
        String larq = laxx.getString("larq");
        String laay = laxx.getString("laay");
        String sycx = laxx.getString("sycx");
        String sasj = laxx.getString("sasj");
        String jbfy = laxx.getString("jbfy");

        fsFullView.setAjmc(ajmc);
        if (StringUtils.isNotBlank(larq)) fsFullView.setLarq(larq);
        if (StringUtils.isNotBlank(laay)) fsFullView.setLaay(laay);
        if (StringUtils.isNotBlank(sycx)) fsFullView.setSycx(sycx);
        if (StringUtils.isNotBlank(sasj)) fsFullView.setSasj(sasj);
        if (StringUtils.isNotBlank(jbfy)) fsFullView.setJbfy(jbfy);

        JSONObject slxx = jbxx.getJSONObject("slxx");
        if (slxx != null) {
            String cbts = slxx.getString("cbts");
            String cbr = slxx.getString("cbr");
            if (StringUtils.isNotBlank(cbts)) fsFullView.setCbts(cbts);
            if (StringUtils.isNotBlank(cbr)) fsFullView.setCbr(cbr);
        }
        JSONObject jaxx = jbxx.getJSONObject("jaxx");
        if (jaxx != null) {
            String zdslfy = jaxx.getString("zdslfy");
            String jafs = jaxx.getString("jafs");
            String jarq = jaxx.getString("jarq");
            String jaay = jaxx.getString("jaay");
            if (StringUtils.isNotBlank(zdslfy)) fsFullView.setZdslfy(zdslfy);
            if (StringUtils.isNotBlank(jafs)) fsFullView.setJafs(jafs);
            if (StringUtils.isNotBlank(jarq)) fsFullView.setJarq(jarq);
            if (StringUtils.isNotBlank(jaay)) fsFullView.setJaay(jaay);
        }
        if (!json.getJSONArray("tsxxs").isEmpty()) {
            JSONObject tsxxs = (JSONObject) json.getJSONArray("tsxxs").get(0);
            if (tsxxs != null) {
                String ftmc = tsxxs.getString("ftmc");
                String ftyt = tsxxs.getString("ftyt");
                String kssj = tsxxs.getString("kssj");
                String jssj = tsxxs.getString("jssj");
                String gksl = tsxxs.getString("gksl");
                if (StringUtils.isNotBlank(ftmc)) fsFullView.setFtmc(ftmc);
                if (StringUtils.isNotBlank(ftyt)) fsFullView.setFtyt(ftyt);
                if (StringUtils.isNotBlank(kssj)) fsFullView.setKssj(kssj);
                if (StringUtils.isNotBlank(jssj)) fsFullView.setJssj(jssj);
                if (StringUtils.isNotBlank(gksl)) fsFullView.setGksl(gksl);
            }
        }
        if (lawyer != null) {
            fsFullView.setDlrid(lawyer.getId());
            fsFullView.setDlr(lawyer.getXm());
        }
        if (fsFullView.getId() == null) {
            fsFullViewService.insertFsFullView(fsFullView);
        } else {
            fsFullViewService.updateFsFullView(fsFullView);
        }
    }

    /**
     * 测试
     */
    @GetMapping("/initCaseDz")
    public AjaxResult initCaseDz() {
        FsCase query = new FsCase();
        List<FsCase> cases = fsCaseService.selectFsCaseList(query);
        for (int i = 0; i < cases.size(); i++) {
            FsCase fsCase = cases.get(i);
            if (fsCase.getFyid() != null && fsCase.getBatchId() != null && fsCase.getSfid() == null) {
                FsCourt court = fsCourtService.selectFsCourtByFyId(fsCase.getFyid());
                FsAddress qx = fsAddressService.selectFsAddressByCode(court.getDzCode());
                FsAddress s = null;
                FsAddress sf = null;
                if (qx != null) {
                    s = fsAddressService.selectFsAddressByCode(qx.getPcode());
                    if (s != null) {
                        sf = fsAddressService.selectFsAddressByCode(s.getPcode());
                        if (sf == null) {
                            sf = s;
                            s = qx;
                            qx = null;
                        }
                    }
                }
                String addr = "";
                if (sf != null) {
                    fsCase.setSfid(sf.getId());
                    addr += sf.getName();
                    int num = sf.getCaseCount();
                    num++;
                    sf.setCaseCount(num);
                    fsAddressService.updateFsAddress(sf);
                }
                if (s != null) {
                    fsCase.setSid(s.getId());
                    addr += s.getName();
                    int num = s.getCaseCount();
                    num++;
                    s.setCaseCount(num);
                    fsAddressService.updateFsAddress(s);
                }
                if (qx != null) {
                    fsCase.setQxid(qx.getId());
                    addr += qx.getName();
                    int num = qx.getCaseCount();
                    num++;
                    qx.setCaseCount(num);
                    fsAddressService.updateFsAddress(qx);
                }
                System.out.println(fsCase.getNbajbh() + ":" + addr);
                int cnum = court.getCaseCount();
                cnum++;
                court.setCaseCount(cnum);
                fsCourtService.updateFsCourt(court);
                fsCaseService.updateFsCase(fsCase);
            }
        }
        return success();
    }


    /**
     * 测试
     */
    @GetMapping("/initFp")
    public AjaxResult initFp(@RequestParam(value = "batchId", required = true) Long batchId) {
//        FsCase query = new FsCase();
//        query.setBatchId(batchId);
//        List<FsCase> cases = fsCaseService.selectFsCaseList(query);
//        for (int i = 0; i < cases.size(); i++) {
//            FsCase fsCase = cases.get(i);
//            String detail = fsCase.getDetailInfo();
//            JSONObject obj = JSONObject.parseObject(detail);
//            String shdh = obj.getString("shdh");
//
//            SysUser user = null;
//            if (shdh.equals("19073173613")) {
//                user = sysUserService.selectUserByUserName("tj001");
//            }
//            if (shdh.equals("19073173691")) {
//                user = sysUserService.selectUserByUserName("tj002");
//            }
//            if (shdh.equals("19073172935")) {
//                user = sysUserService.selectUserByUserName("tj003");
//            }
//            if (shdh.equals("19073172875")) {
//                user = sysUserService.selectUserByUserName("tj004");
//            }
//            if (user != null) {
//                fsCase.setTjyId(user.getUserId());
//                fsCase.setTjy(user.getNickName());
//                fsCaseService.updateFsCase(fsCase);
//            }
//            System.out.println(fsCase.getNbajbh() + ":" + fsCase.getTjy());
//        }


        try {
            FileInputStream inputStream = new FileInputStream(new File("/Users/hero/Documents/fsaj/桔子/第一批/案件要素表.xlsx"));
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            Map<String, String> tjyMap = new HashMap<>();
            for (Row row : sheet) { // 迭代每一行
                int num = row.getRowNum();
                if (num > 0) {
                    String nbajbh = "";
                    String tjy = "";
                    for (Cell cell : row) { // 迭代每一列
                        int cnum = cell.getColumnIndex();
                        if (cnum == 4) {
                            nbajbh = cell.getStringCellValue();
                        }
                        if (cnum == 7) {
                            tjy = cell.getStringCellValue();
                        }
                    }
                    System.out.println(nbajbh + " : " + tjy);
                    FsCase fsCase = fsCaseService.selectFsCaseByNbbh(nbajbh);
                    if (fsCase != null) {
                        SysUser user = null;
                        if (tjy.contains("tj001")) {
                            user = sysUserService.selectUserByUserName("tj001");
                        }
                        if (tjy.contains("tj002")) {
                            user = sysUserService.selectUserByUserName("tj002");
                        }
                        if (tjy.contains("tj003")) {
                            user = sysUserService.selectUserByUserName("tj003");
                        }
                        if (tjy.contains("tj004")) {
                            user = sysUserService.selectUserByUserName("tj004");
                        }
                        if (user != null) {
                            fsCase.setTjyId(user.getUserId());
                            fsCase.setTjy(user.getNickName());
                            fsCaseService.updateFsCase(fsCase);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success();
    }


    @GetMapping("/initCaseSszt")
    public AjaxResult initCaseSszt() {
        FsCase query = new FsCase();
        List<FsCase> cases = fsCaseService.selectFsCaseList(query);
        for (int i = 0; i < cases.size(); i++) {
            FsCase fsCase = cases.get(i);
            System.out.println(fsCase.getNbajbh() + " : " + fsCase.getAjmc());
//            if (fsCase.getSsztid() == null) {
            FsClient client = fsClientService.selectFsClientById(fsCase.getYg());
            if (client != null) {
                FsCapital capital = fsCapitalService.selectFsCapitalByName(client.getDwmc());
                if (capital != null) {
                    fsCase.setSsztid(capital.getId());
                    fsCase.setSsztmc(capital.getDwmc());
                    fsCaseService.updateFsCase(fsCase);
                }
            }
//            }
        }
        return success();
    }
}
